from django.db import models
from datetime import datetime
from record.settings import MEDIA_ROOT
from django.db.models.signals import post_delete
from django.dispatch import receiver
import os


# Create your models here.
class NoteType(models.Model):
    id = models.AutoField(primary_key=True)
    create_time = models.DateTimeField(default=datetime.now)
    update_time = models.DateTimeField(default=datetime.now)

    value = models.CharField(max_length=50, verbose_name='笔记类型', default='')

    def __str__(self):
        return self.value

# def upload_to(instance, filename):
#     path = '%s_%s'%(instance.title, filename)
#     return path

class NoteRecord(models.Model):
    id = models.AutoField(primary_key=True)
    create_time = models.DateTimeField(default=datetime.now)
    update_time = models.DateTimeField(default=datetime.now)
    #笔记类型
    note_type = models.ForeignKey(to=NoteType,on_delete=models.CASCADE)
    #标题
    title = models.CharField(max_length=50, verbose_name='标题')
    #笔记内容
    content = models.TextField(verbose_name='笔记内容', default='')
    #附件
    appendix = models.FileField(verbose_name='附件', default='', max_length=200, null=True, blank=True)

    def __str__(self):
        return '笔记记录'

## 添加监听器
@receiver(post_delete, sender=NoteRecord)
def delete_upload_files(sender, instance, **kwargs):
    files = getattr(instance, 'appendix')
    if not files:
        return
    fname = os.path.join(MEDIA_ROOT, str(files))
    if os.path.isfile(fname):
        os.remove(fname)